package com.cosytek.farmmanager;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

public class WebSocketService extends Service implements WebSocketWrapper.OnWebSocketListener {
    private static final String TAG = "WebSocketService";
    private String mAccount;
    private String mPassword;
    private WebSocketWrapper mWebSocketWrapper;
    private Handler mWorkHandler;
    private final static String mWSPath = "/ws";
    public static final int RECONNECT_PERIOD = 10 * 1000;

    public static void startWebSocketService(Context c) {
        Intent intent = new Intent(c, WebSocketService.class);
        if (c.startService(intent) == null) {
            Log.e(TAG, "start WebSocketService failed");
        } else {
            Log.e(TAG, "start WebSocketService succeed ");
        }
    }

    public static void stopWebSocketService(Context c) {
        Intent intent = new Intent(c, WebSocketService.class);
        c.stopService(intent);
    }

    public WebSocketService() {
        mWorkHandler = new Handler();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            mAccount = intent.getStringExtra(LoginFragment.KEY_ACCOUNT);
            mPassword = intent.getStringExtra(LoginFragment.KEY_PASSWORD);
        }

        if (TextUtils.isEmpty(mAccount) || TextUtils.isEmpty(mPassword)) {
            loadLoginData();
        }

        startWebSocket();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mWorkHandler.removeCallbacksAndMessages(null);
        stopWebSocket();
    }

    private void loadLoginData() {
        SharedPreferences share = this.getSharedPreferences(LoginFragment.LOGIN_DATA_CATALOG, Context.MODE_PRIVATE);
        mAccount = share.getString(LoginFragment.KEY_ACCOUNT, "");
        mPassword = share.getString(LoginFragment.KEY_PASSWORD, "");
    }

    private void startWebSocket() {
        if (TextUtils.isEmpty(mAccount) || TextUtils.isEmpty(mPassword)) {
            return;
        }

        doConnect();
    }

    private void stopWebSocket() {
        if (mWebSocketWrapper == null) {
            return;
        }

        mWebSocketWrapper.close();
        mWebSocketWrapper = null;
    }

    private void doConnect() {
        if (mWebSocketWrapper != null) {
            return;
        }

        String serverAddress = FarmManagerApp.getAppContext().getString(R.string.server_address);
        mWebSocketWrapper = new WebSocketWrapper(serverAddress+mWSPath,
                mAccount, mPassword, this);

        mWebSocketWrapper.connect();
    }

    @Override
    public void onStringReceived(final String data) {
        mWorkHandler.post(new Runnable() {
            @Override
            public void run() {
                MsgManager.instance().onMsgReceived(data);
            }
        });
    }

    @Override
    public void onWebSocketBreak() {
        Log.e(TAG, "WebSocket break, reconnect later");
        mWebSocketWrapper = null;
        delayRetryConnect();
    }

    @Override
    public Handler getWorkHandler() {
        return mWorkHandler;
    }

    private void delayRetryConnect() {
        mWorkHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                doConnect();
            }
        }, RECONNECT_PERIOD);
    }

}
